#include "connection.h"
#include "request.h"
#include "httpserver.h"
#include "playlist.h"

#include <QUrl>
#include <QFile>

#include <QtDebug>
#include "collection/collection.h"

Connection::Connection(HttpServer* _parent, QTcpSocket* _sock) :
    sock(_sock), server(_parent)
{
    _sock->setParent(this);
}

void Connection::handle()
{
    qDebug() << "New connection incoming";
    connect(sock, SIGNAL(readyRead()), this, SLOT(readNext()));
    readNext();
}

void Connection::readNext()
{
    request.append(sock->readAll());

    if(requestIsComplete())
        executeRequest();
}

bool Connection::requestIsComplete()
{
    return request.contains("\r\n\r\n");
}

void Connection::executeRequest()
{
    disconnect(this, SLOT(readNext()));
    QStringList lines = QString(request).split("\r\n");
    Request request(lines);

    if(request.uri == "/list")
        sendList();
    else if(request.uri.startsWith("/get/"))
        sendFile(request.uri);
    else if(request.uri.startsWith("/track/"))
        sendTrackPlaylist(request.uri, request.host);
    else if(request.uri.startsWith("/album/"))
        sendAlbumPlaylist(request.uri, request.host);
    else if(request.uri.startsWith("/artist/"))
        sendArtistPlaylist(request.uri, request.host);
    else
        sendIndex();

    connect(sock, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten()));
}

void Connection::sendList()
{
    sock->write("HTTP/1.0 200 OK\n");
    sock->write("Content-Type: text/xml\n");
    sock->write("Connection: close\n\n");
    sock->write(server->xml().toUtf8());
}

void Connection::bytesWritten()
{
    if(sock->bytesToWrite() == 0)
    {
        sock->close();
        delete this;
    }
}

void Connection::sendFile(QString uri)
{
    QString id = uri.split('/').at(2);
    QString url = server->collection()->getTrackPath(id.toInt());
    QFile f(url);
    f.open(QIODevice::ReadOnly);
    qDebug() << url << ";exists=" << f.exists();

    QString filename = url.split("/").last();
    qint64 size = f.size();

    sock->write("HTTP/1.0 200 OK\n");
    sock->write(QString("Content-Disposition: attachment; filename=\""+filename+"\"\n").toAscii());
    sock->write("Content-Type: audio/mpeg\n");
    sock->write("Connection: keep-alive\n");
    sock->write(QString("Content-Length: "+QString::number(size)+"\n").toAscii());
    sock->write("Accept-Ranges: bytes\n");

    sock->write("\n");

    while(!f.atEnd())
    {
        QByteArray a = f.read(10240);
        sock->write(a);
    }
}

void Connection::sendIndex()
{
    sock->write("HTTP/1.0 200 OK\n");
    sock->write("Content-Type: text/html;\n");
    sock->write("\n");

    QFile f("index.html");
    f.open(QIODevice::ReadOnly);
    sock->write(f.readAll());
}

void Connection::sendTrackPlaylist(QString uri, QString host)
{
    if(uri.endsWith(".m3u"))
        uri = uri.left(uri.length()-4);

    QString trackId = uri.split('/').at(2);

    Playlist playlist;
    playlist.addTrack(QUrl(QString("http://") + host + "/get/" + trackId), "Patchwork Streaming");

    QByteArray file = playlist.toString().toLatin1();

    sock->write("HTTP/1.0 200 OK\n");
    sock->write("Content-Type: audio/x-mpegurl\n");
    //sock->write("Content-Disposition: attachment; filename=\"playlist.m3u\"\n");
    sock->write("Connection: keep-alive\n");
    sock->write(QString("Content-Length: "+QString::number(file.size())+"\n").toAscii());
    sock->write("Accept-Ranges: bytes\n");
    sock->write("\n");

    sock->write(file);
}

void Connection::sendAlbumPlaylist(QString uri, QString host)
{
    QString albumId = uri.split('/').at(2);
}

void Connection::sendArtistPlaylist(QString uri, QString host)
{
    QString artistId = uri.split('/').at(2);
}

